//
//  NetworkAPI.m
//  IconMaster
//
//  Created by nhn on 14-9-16.
//  Copyright (c) 2014年 为为. All rights reserved.
//

#import "NetworkAPI.h"
#import "AFNetworking.h"
#import "DBOperation.h"

#define API_PATH        @"/api.php"

@implementation NetworkAPI

+ (NetworkAPI *)sharedInstance
{
    static dispatch_once_t once;
    static NetworkAPI* instance = nil;
    
    dispatch_once(&once, ^{
        instance = [[self alloc] init];
    });
    
    return instance;
}

- (id)init
{
    self = [super init];
    if (self) {
        self.baseUrl = [DBOperation baseUrl];
    }
    return self;
}

- (void)command:(NSString *)command withParameter:(NSDictionary *)params onComplete:(void (^)(NSDictionary *))completeBlock
{
    if (!params) {
        params = [NSMutableDictionary dictionary];
    }
    
    NSMutableDictionary* mutableParams = nil;
    if ([params isKindOfClass:[NSMutableDictionary class]]) {
        mutableParams = (NSMutableDictionary*)params;
    } else {
        mutableParams = [NSMutableDictionary dictionaryWithDictionary:params];
    }
    [mutableParams setObject:command forKey:@"command"];
    
    NSString* urlString = [self.baseUrl stringByAppendingString:API_PATH];
   
    [[AFHTTPSessionManager manager] GET:urlString parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (completeBlock) {
            completeBlock(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (completeBlock) {
            completeBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:@"error"]);
        }

    }];
//    [[AFHTTPRequestOperationManager manager] jsonPOST:urlString
//                                           parameters:params
//                                              success:^(AFHTTPRequestOperation *operation, id responseObject) {
//                                                  if (completeBlock) {
//                                                      completeBlock(responseObject);
//                                                  }
//                                              }
//                                              failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//                                                  if (completeBlock) {
//                                                      completeBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:@"error"]);
//                                                  }
//                                              }];
}

- (NSString *)urlStringForPath:(NSString *)path {
//	NSString* siteBase = [self.baseUrl stringByReplacingOccurrencesOfString:@"http://" withString:@""];
	return [self.baseUrl stringByAppendingFormat:@"/%@",path];
}

@end
